/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eulerframework;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Thor
 */
public class EulerConnection {

    WebsiteParser parser;
    URL url;
    HttpCookie cookie;
    
    public EulerConnection(WebsiteParser parser){
        this.parser = parser;
        try {
            url = new URL(parser.getURL());
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    public void postGuess(String guess, String captcha) {
        try {
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("guess", guess);
            con.setRequestProperty("captcha", captcha);
            con.setRequestProperty("Cookie", cookie.getValue());
            con.connect();
            BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = input.readLine();
            StringBuilder sb = new StringBuilder();
            while (line != null) {
                sb.append(line);
                line = input.readLine();
            }
            System.out.println("Server respone: " + sb);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void postLogin(String username, String password){
        try {
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("username", username);
            con.setRequestProperty("password", password);
            con.connect();
            BufferedReader input = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = input.readLine();
            StringBuilder sb = new StringBuilder();
            while (line != null) {
                sb.append(line);
                line = input.readLine();
            }
            System.out.println("Login server respone: " + sb);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
